package com.leigang.swagger.config;

import com.alibaba.fastjson.JSON;
import com.google.common.base.Stopwatch;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author leigang
 * @description: 控制器请求参数打印
 * @date 20/8/12  22:27
 */
@Slf4j
@Aspect
@Configuration
public class ControllerAspect {

    @Pointcut("execution(* com.leigang.swagger.controller..*.*(..))")
    public void methodArgs() {

    }

    @Around("methodArgs()")
    public Object invoke(ProceedingJoinPoint joinPoint) throws Throwable {
        Object result;
        Stopwatch stopwatch = Stopwatch.createStarted();
        result = joinPoint.proceed();
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            // 请求路径
            String requestUrl = request.getRequestURL().toString();
            String method = request.getMethod();

            // 构造参数组集合
            Object[] args = joinPoint.getArgs();
            String params = "";
            for (Object arg : args) {
                params+=arg;
            }

//            log.info("请求方法名 : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
            stopwatch.stop();
            long timeConsuming = stopwatch.elapsed(TimeUnit.MILLISECONDS);
            log.info("\n请求URL:"+requestUrl+"\n请求类型:"+method+"\n请求参数:"+params+"\n请求结果:"+result+"\n请求耗时:"+timeConsuming+"\n");
        } catch (Exception e) {
            log.error("参数获取异常: {}", e.getMessage());
        }

        return result;
    }

}
